package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrEntityVO;
import com.atguigu.gulimall.product.vo.AttrRespVO;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;


@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService  categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAttrEntity(AttrEntityVO attrEntityVO) {
        //首先将结果进行保存
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrEntityVO, attr);
        this.save(attr);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrEntityVO.getAttrGroupId() != null) {
            //保存关联关系
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrGroupId(attrEntityVO.getAttrGroupId());
            entity.setAttrId(attr.getAttrId());
            attrAttrgroupRelationService.save(entity);
        }

    }

    @Override
    public PageUtils getBaseList(Map<String, Object> params,Long catLogId,String type) {
        //首先获取查询的参数
        String key = (String) params.get("key");
        //创建一个查询条件
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        queryWrapper.eq("attr_type","base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        //判断是否为空
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(obj ->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        if (catLogId != 0){
            queryWrapper.eq("catelog_id",catLogId);
        }
        //执行查询
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),queryWrapper);
        //新的返回对象
        IPage<AttrRespVO> respPage = new Page<>();
        BeanUtils.copyProperties(page, respPage);
        //获取到分页查询的值
        List<AttrEntity> records = page.getRecords();
        //进行数据的处理
        List<AttrRespVO> respVOList = records.stream().map((attrEntity) ->{
            AttrRespVO respVO = new AttrRespVO();
            BeanUtils.copyProperties(attrEntity, respVO);
            if ("base".equals(type)){
                //设置分组名称
                //1.首先根据id将pms_attr_attrgroup_relation中的信息进行查询
                LambdaQueryWrapper<AttrAttrgroupRelationEntity> lambdaQueryWrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>();
                //2.设置查询条件
                lambdaQueryWrapper.eq(AttrAttrgroupRelationEntity::getAttrId,attrEntity.getAttrId());
                //3.获取到了组的id
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(lambdaQueryWrapper);
                if (!ObjectUtils.isEmpty(relationEntity) && relationEntity.getAttrGroupId() != null) {
                    //4.进行查询,并赋值
                    AttrGroupEntity entity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    respVO.setGroupName(entity.getAttrGroupName());
                }
            }
            //设置分类名称
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (!ObjectUtils.isEmpty(categoryEntity)){
                respVO.setCatelogName(categoryEntity.getName());
            }

            return respVO;
        }).collect(Collectors.toList());
        //将结果进行重新赋值
        respPage.setRecords(respVOList);
        //进行返回
        return new PageUtils(respPage);
    }

    /**
     * 根据id获取详细信息
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVO getDetailById(Long attrId) {
        //首先查询出基本信息
        AttrEntity attrEntity = this.getById(attrId);
        //创建返回类型
        AttrRespVO respVO = new AttrRespVO();
        //进行赋值
        BeanUtils.copyProperties(attrEntity, respVO);
        //设置分类的全路径
        List<Long> paths = new ArrayList<>();
        List<Long> categoryPath = findCategoryPath(respVO.getCatelogId(), paths);
        Collections.reverse(categoryPath);
        respVO.setCatelogPath(paths.toArray(new Long[categoryPath.size()]));
        if (attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())){
            //设置分组的id
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> lambdaQueryWrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>();
            lambdaQueryWrapper.eq(AttrAttrgroupRelationEntity::getAttrId,respVO.getAttrId());
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(lambdaQueryWrapper);
            if (!ObjectUtils.isEmpty(relationEntity)){
                respVO.setAttrGroupId(relationEntity.getAttrGroupId());
            }
        }

        return respVO;
    }

    @Override
    public void updateAttr(AttrEntityVO attrEntityVO) {
        //首先修改自己的数据
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attrEntityVO , entity);
        //执行修改
        this.updateById(entity);
        //接下来修改分组数据中的信息
        //当修改的组别为空时候
        if (entity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())){
            if (ObjectUtils.isEmpty(attrEntityVO.getAttrGroupId())){
                //将原来的组别进行删除
                LambdaQueryWrapper<AttrAttrgroupRelationEntity> delWrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>();
                delWrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attrEntityVO.getAttrId());
                attrAttrgroupRelationService.remove(delWrapper);
            }else {
                //判断是新增还是修改
                int num = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntityVO.getAttrId()));
                //创建参数
                AttrAttrgroupRelationEntity attrgroupRelation = new AttrAttrgroupRelationEntity();
                //进行赋值
                attrgroupRelation.setAttrId(attrEntityVO.getAttrId());
                attrgroupRelation.setAttrGroupId(attrEntityVO.getAttrGroupId());
                //执行修改操作
                if (num > 0) {
                    //创建修改的条件
                    UpdateWrapper<AttrAttrgroupRelationEntity> wrapper = new UpdateWrapper<>();
                    wrapper.eq("attr_id",attrEntityVO.getAttrId());
                    //执行修改
                    attrAttrgroupRelationService.update(attrgroupRelation,wrapper);
                }else {
                    //执行新增操作
                    attrAttrgroupRelationService.save(attrgroupRelation);
                }
            }
        }
    }

    @Override
    public void removeAttrIds(List<Long> list) {
        //首先执行删除代码
        this.removeByIds(list);
        //将pms_attr_attrgroup_relation表中的数据也进行删除
        LambdaQueryWrapper<AttrAttrgroupRelationEntity> delWrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>();
        delWrapper.in(AttrAttrgroupRelationEntity::getAttrId, list);
        attrAttrgroupRelationService.remove(delWrapper);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return baseMapper.selectSearchAttrs(attrIds);
    }

    private List<Long> findCategoryPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        //首先查询出来当前分类的详情
        CategoryEntity category = categoryService.getById(catelogId);
        if (category.getParentCid() != 0){
            findCategoryPath(category.getParentCid(),paths);
        }
        return paths;
    }

}